<template>
  <div class="main-wrap">
    <div class="context-warp">
      <el-card>
        <div class="tool-wrap">
          <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        </div>
        <el-table :data="tableList" height="510px" v-loading="tableLoading">
          <el-table-column prop="id" label="id" width="100"/>
          <el-table-column prop="username" label="用户名称"/>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              {{ scope.row.status == 1 ? '正常' : '禁用' }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="创建时间" width="180"/>
          <el-table-column prop="createTime" label="创建时间" width="180"/>
        </el-table>
      </el-card>
    </div>

    <el-dialog v-model="addUserFlag"
               title="添加用户"
               :center="true"
    >
      <el-form :model="userForm">
        <el-form-item label="用户名称:">
          <el-input v-model="userForm.username" placeholder="请输入用户名称" clearable/>
        </el-form-item>
        <el-form-item label="登录密码:">
          <el-input v-model="userForm.password" placeholder="请输入密码" type="password" show-password clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addUserFlag = false">取 消</el-button>
          <el-button type="primary" @click="handleAddUserConfirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { userList, UserData, addUser, AddUserParam } from "@/api/UserApi.ts"
import { ElMessage } from "element-plus"

const tableList = ref<Array<UserData>>([])
const tableLoading = ref<boolean>(false)
const addUserFlag = ref<boolean>(false)
const userForm = ref<AddUserParam>({
  username: '',
  password: ''
})

onMounted(() => {
  queryUsers()
})

const queryUsers = async () => {
  tableLoading.value = true
  const rs = await userList()
  tableLoading.value = false
  tableList.value = rs.data ? rs.data : []
}

const handleAddUser = () => {
  userForm.value = {
    username: '',
    password: ''
  }
  addUserFlag.value = true
}

const handleAddUserConfirm = async () => {
  const rs = await addUser(userForm.value)
  if(rs.code == '200'){
    ElMessage.success("添加成功")
    addUserFlag.value = false
    await queryUsers()
  }
}
</script>

<style lang="less" scoped>
.main-wrap{
  padding: 50px 50px 50px;
  display: flex;
  justify-content: center;

  .context-warp{
    width: 900px;
    height: 600px;

    .tool-wrap{
      width: 100%;
      height: 80px;
      padding-bottom: 10px;
      display: flex;
      justify-content: flex-end;
      align-items: end;
    }
  }
}
</style>